package org.shop.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.shop.dao.Impl.ProductDaoImpl;
import org.shop.dao.ProductDao;
import org.shop.entity.Product;
import org.shop.vo.PageVo;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 查询商品信息支持分页和条件查询(商品名称，商品类型)
 *
 * @author ZJL
 * @date 2024-12-11
 */
@WebServlet("/list_page_condition.do")
public class ListProductByPageAndConditionServlet extends BaseController {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        //获取表单中输入的数据
        // 1.1）当前页
        String page = req.getParameter("page");
        // 1.2）每页记录数
        String limit = req.getParameter("limit");
        // 1.3）查询条件一：商品名称
        String productName = req.getParameter("productName");
        // 1.4）查询条件二：商品类型
        String productType = req.getParameter("productType");

        //验证数据的合法性 - 正则表达式
        int intPage = 1;
        if (page != null && page.matches("\\d{1,}")) {
            intPage = Integer.parseInt(page);
        }

        int intLimit = 5;
        if (limit != null && limit.matches("\\d{1,}")) {
            intLimit = Integer.parseInt(limit);
        }

        Product product = new Product();
        product.setProductName(productName);
        product.setProductType(productType);


        //实例化 DAO
        ProductDao productDao = new ProductDaoImpl();
        //调用 DAO 对象的方法 - 条件查询商品信息
        List<Product> list = productDao.selectByPage(product, intPage, intLimit);
        //条件查询总记录数
        Long count = productDao.selectByPageCount(product);

        print(resp,success(list,count));
    }
}
